<template>
    <div class="components_edit_modal">
        <el-dialog width="80%" :title="title" :visible.sync="state" :show-close="true" :close-on-click-modal="false" fullscreen center>
            <el-form ref="formInfo" :model="formInfo" :rules="formRules" label-width="95px" size="mini">

                <el-form-item label="活动标题：" prop="title">
                    <el-input placeholder="请输入活动标题" clearable v-model="formInfo.title"></el-input>
                </el-form-item>

                <el-form-item label="截止时间：" prop="title">
                    <el-date-picker
                        v-model="formInfo.deadline"
                        align="right"
                        type="date"
                        placeholder="选择活动截止时间">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="年龄阶段：" prop="ageTypeId">
                    <el-select v-model="formInfo.ageTypeId" filterable placeholder="请选择相年龄阶段">
                        <el-option
                            v-for="item in options"
                            :key="item.id"
                            :label="item.dictValue"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="用户列表：" prop="userId">
                    <el-select v-model="formInfo.userId" filterable remote reserve-keyword placeholder="请选择用户"
                    :remote-method="remoteMethod"
                    :loading="loading">
                        <el-option
                            v-for="item in userOptions"
                            :key="item.id"
                            :label="item.login"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="底片链接：" prop="urls">
                    <el-tag type="danger" style="mragin-bottom: 10px;">请先上传富文本中使用的图片！！</el-tag>
                    <el-select v-model="formInfo.urls" multiple  placeholder="请选择" style="display:none;">
                        <el-option
                            v-for="item in options"
                            :key="item.id"
                            :label="item.dictValue"
                            :value="item.id">
                        </el-option>
                    </el-select>
                    <pl-upload
                        :postData="attachment"
                        :displaymode="'images'"
                        :api="'jstn-pic'"
                        :imageOnly="false"
                        :buttonIds='{select:"selectfiles1",upload:"postfiles1",container:"container1"}'
                        @reloadFiles="reloadFiles" ></pl-upload>
                </el-form-item>
            </el-form>
             <!-- 组件有两个属性 value 传入内容双向绑定 setting传入配置信息 --> 
            <editor class="editor" 
            :value="formInfo.description"  
            :setting="editorSetting" 
            @input="updateContent"></editor>  

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" @click="addinfo">确 定</el-button>
                <el-button @click="state = false" size="small">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import editor from '../../../common/editor'
    import PlUpload from "../../../common/PlUpload"
    export default {
        components: {
            editor,
            "pl-upload":PlUpload
        },
        data() {
            return {
                state: false,
                title:'',
                content:'我是富文本编辑器的内容',  
                //tinymce的配置信息 参考官方文档 https://www.tinymce.com/docs/configure/integration-and-setup/  
                editorSetting:{  
                    height:400,  
                },
                loading:false,
                attachment:[],
                formInfo:{
                    activityStatus:null,
                    ageTypeId:null,
                    deadline:null,
                    title:null,
                    typeId: null,
                    userId:null,
                    urls:['0'],
                    description:'请输入文本内容………………',
                    // photos:[]
                },
                formRules:null,
                options:[],
                userOptions:[]
            }
        },
        created() {},
        mounted() {
            this.getAgeType();
        },
        computed: {},
        methods: {
            showDialog(val) {
                if (this.$refs['formInfo'] !== undefined) {
                    this.$refs['formInfo'].resetFields();
                }
                this.attachment = [];
                this.formInfo.description = '';
                if (typeof(val) == 'object') {
                    for (var key in val) {
                        this.formInfo[key] = val[key];
                    }
                    this.title = "编辑活动";
                    this.type = "edit";
                    
                    this.attachment = val.photos?val.photos:[];
                    this.attachment.forEach((item,idnex)=>{
                        item.isImage = item.true;
                        item.url = item.url;


                        item.bucket = this.urlFormat(item.url).bucket;
                        item.object = this.urlFormat(item.url).objectKey;
                        item.fileType = this.urlFormat(item.url).fileType;

                        if ( $.inArray(item.fileType, ["jpg", "jpeg","image/jpeg", "gif", "png", "bmp"]) < 0 ) {
                            item["isImage"] = false;
                            item["imgsrc"] = "/static/js/plupload/suffix/otherfile.png";
                        }else{
                            item["isImage"] = true;
                            item["imgsrc"] = item.url;
                        }
                    })
                } else {

                    this.title = "添加活动";
                    this.type = "add";
                    this.formInfo.typeId = val;
                }
                console.log("this.attachment");
                console.log(this.attachment);
                console.log(this.formInfo);
                this.state = true;
            },
            updateContent(data){//触发子组件城市选择-选择城市的事件
                this.formInfo.description = data;//改变了父组件的值  
            },
            addinfo() {
                let vm = this;
                vm.$refs.formInfo.validate(valid => {
                    if (valid) {
                        let submission = ""; //提交方式
                        //选择提交方式
                        if (vm.type == "edit") {
                            submission = "put";
                        } else {
                            submission = "post";
                        }
                        // 提交
                        this.axios({
                            method: submission,
                            url: api.circleManagement.circleList,
                            data: vm.formInfo
                        }).then(response => {
                            if (response.data.code == 200) {
                                console.log(response.data);
                                vm.state = false;
                                vm.$parent.$refs.tableList.$emit("vuetable:refresh");
                                vm.$message.success(response.data.message);
                            } else {
                                vm.$message.error(response.data.message);
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            // 获取字典项的信息
            getAgeType(){
                let vm = this;
                this.axios.get(api.dictionary.dictList + "?type=AGE").then(response => {
                    if (response.data.code == 200) {
                        this.options = response.data.data.dataList;
                    } else {
                        this.$message({
                            message: response.data.message,
                            type: "error",
                            center: true
                        });
                    }
                });
            },
            reloadFiles: function (files) {
                console.log(files)
                let vm = this;
                this.attachment = [];
                vm.formInfo.urls = [];
                files.forEach((item,idnex)=>{
                    item.url = item.fileStoreName;
                    vm.attachment.push(item);
                    console.log(vm.formInfo.urls);
                    console.log(item.url);
                    vm.formInfo.urls.push(item.url);
                })
                // this.film.url = this.attachment[0].url;
            },
            // 格式化 url 地址
            urlFormat(strUrl){
                // var strUrl = "https://jstn-pic.oss-cn-qingdao.aliyuncs.com/d16e8272-4ac7-de6a-1071-a79ded59d29a.jpg"
                var arrUrl = strUrl.split("//")[1].split("/");
                var objectKey = arrUrl[1];
                var bucket = arrUrl[0].split(".")[0];
                var fileType = arrUrl[1].split(".")[1];
                var resultObject ={
                    bucket : bucket,
                    objectKey : objectKey,
                    fileType : fileType
                }
                return resultObject
            },
            //  用户信息异步检索
            remoteMethod(query) {
                if (query !== '' && query.length>2 ) {
                    this.loading = true;
                    setTimeout(() => {
                        this.loading = false;
                        this.getUserList(query);
                    }, 200);
                } else {
                    this.userOptions = [];
                }
            },
            // 获取用户数据
            getUserList(name) {
                let vm = this;
                vm.axios.get(api.userManagement.userList_no + "?keyWord=" + name).then((response) =>{
                    if (response.data.code == 200) {
                        vm.userOptions = response.data.data;
                    } else {
                        Message({
                            message: response.data.msg,
                            type: 'error'
                        });
                    }
                })
            },
        },
    };
</script>
<style lang="less">
#mceu_15{ margin-top: 10px;}
</style>